<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('publication.publicationInfo')"
    width="1200"
    @close="onDialogClose"
    :destroy-on-close="true"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formEdit"
      :rules="rules"
      label-position="top"
      label-width="120px"
    >
      <el-container>
        <!-- fix el-affix 在 el-dialog\el-row 中无效，滚动时 toolbar 移动到这里，还原时 toolbar 复位 -->
        <el-affix
          id="affix-container"
          style="position: absolute; z-index: 1400; margin-left: 20px"
          :offset="0"
          @scroll="handleAffixScroll"
        >
        </el-affix>
        <el-main style="padding-top: 0px">
          <el-row>
            <el-col>
              <el-form-item
                :label="t('publication.publicationName')"
                prop="publicationName"
              >
                <el-input
                  v-model="formEdit.publicationName"
                  maxlength="256"
                  :placeholder="t('publication.publicationName')"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item
                :label="t('publication.publicationSummary')"
                prop="publicationSummary"
              >
                <el-input
                  v-model="formEdit.publicationSummary"
                  maxlength="256"
                  :placeholder="t('publication.publicationSummary')"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.description')">
                <el-input
                  v-model="formEdit.description"
                  :rows="2"
                  maxlength="1024"
                  type="textarea"
                  :placeholder="t('publication.description')"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.aboutTheAuthor')">
                <el-input
                  v-model="formEdit.aboutTheAuthor"
                  :rows="2"
                  maxlength="1024"
                  type="textarea"
                  :placeholder="t('publication.aboutTheAuthor')"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.tableOfContents')">
                <el-input
                  v-model="formEdit.tableOfContents"
                  :rows="2"
                  maxlength="1024"
                  type="textarea"
                  :placeholder="t('publication.tableOfContents')"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.content')">
                <!-- description aboutTheAuthor tableOfContents -->
                <div class="ck-body-wrapper">
                  <!-- fix 在弹出窗口中 link 之类的 pop 弹出无效问题 -->
                  <!-- https://devs.keenthemes.com/question/ck-editor-5-link-url-not-focussing-when-inside-modal -->
                  <div id="affix-reset-container" style="">
                    <div
                      id="toolbar-container"
                      style="width: 768px; background-color: #fff"
                    ></div>
                  </div>
                  <div id="editor" v-loading="true"></div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-main>

        <el-aside
          style="border-left: 1px solid #efefef; padding-left: 20px"
          width="350px"
        >
          <el-row>
            <el-col>
              <el-form-item :label="t('publication.author')">
                <el-input v-model="formEdit.author" maxlength="64" clearable>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.publisher')">
                <el-input
                  v-model="formEdit.publisher"
                  maxlength="128"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.originalName')">
                <el-input
                  v-model="formEdit.originalName"
                  maxlength="256"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.translator')">
                <el-input
                  v-model="formEdit.translator"
                  maxlength="32"
                  clearable
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.publicationDate')">
                <el-date-picker
                  v-model="state.publicationDate"
                  type="date"
                  class="fix-el-date-picker-width"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.ISBN')">
                <el-input v-model="formEdit.isbn" maxlength="32" clearable>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.pages')">
                <el-input-number
                  v-model="formEdit.pages"
                  :controls="false"
                  max="9999"
                  min="0"
                  class="el-input-number-left-fix"
                  style="width: 100%"
                  clearable
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.price')">
                <el-input-number
                  v-model="formEdit.price"
                  :controls="false"
                  max="9999"
                  min="0"
                  :precision="2"
                  class="el-input-number-left-fix"
                  style="width: 100%"
                  clearable
                >
                </el-input-number>
              </el-form-item>
            </el-col>

            <el-col>
              <el-form-item :label="t('publication.cover')">
                <el-upload
                  ref="logoFileRef"
                  v-model:file-list="logoFileList"
                  accept=".jpg,.jpeg,.png,.gif"
                  :action="apiUpload.uploadUrl()"
                  :headers="headers()"
                  :data="{
                    businessKey: formEdit.publicationId,
                    category: logoFileCategory,
                  }"
                  :limit="1"
                  :on-exceed="handleLogoUploadExceed"
                  :on-success="handleLogoUploadSuccess"
                  list-type="picture-card"
                  ><el-icon><Plus /></el-icon
                  ><template #tip>
                    <div class="el-upload__tip">
                      {{ t("upload.imgTip", { size: 100 }) }}
                    </div>
                  </template></el-upload
                >
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.topIndex')">
                <el-switch
                  v-model="formEdit.top"
                  :active-value="true"
                  :inactive-value="false"
                />
                <el-input-number
                  v-model="formEdit.topIndex"
                  :controls="false"
                  :disabled="!formEdit.top"
                  max="10"
                  min="0"
                  class="el-input-number-left-fix"
                  style="margin-left: 20px; width: 60px"
                  placeholder="排序"
                  clearable
                >
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="t('publication.status')">
                <el-switch
                  v-model="formEdit.status"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-aside>
      </el-container>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-affix position="bottom" :offset="20">
          <el-button @click="state.dialogFormVisible = false">{{
            t("common.cancelButton")
          }}</el-button>
          <el-button type="primary" @click="handleSubmit">{{
            t("common.submitButton")
          }}</el-button>
        </el-affix>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, watch, nextTick, onUnmounted } from "vue";
import { ElInput } from "element-plus";
import { useStore } from "../../../stores/store";
import utils from "../../../utils/utils";
import moment from "moment";
import { Plus } from "@element-plus/icons-vue";
import { headers } from "../../../utils/request";
import apiUpload from "../../admin/api/upload";
import apiCms from "../api/cms";
import apiPublication from "../api/publication";
import DecoupledEditor from "@ckeditor/ckeditor5-build-decoupled-document";
import "@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn";

const env = import.meta.env;
import { useI18n } from "vue-i18n";
import axios from "axios";
const { t } = useI18n({ useScope: "global" });
const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const store = useStore();
const formRef = ref();

const logoFileRef = ref();
const logoFileCategory = "publication-cover";
const logoFileList = ref([]);

const stateOriginal = () =>
  reactive({
    dialogFormVisible: false,
    publicationDate: "",
    tagPage: 1,
    tagMore: true,
    editorData: "",
    editorConfig: {
      // The configuration of the editor.
      language: "zh_CN",
      // ckfinder: {
      //   // 后端处理上传逻辑返回json数据, 包括uploaded 上传的字节数 和url两个字段
      //   uploadUrl: process.env.VUE_APP_BASE_URL + `/upload`,
      // },
    },
  });
const state = reactive(stateOriginal());

const formEditOriginal = () => {
  return {
    publicationId: "",
    publicationName: "",
    publicationSummary: "",
    publisher: "",
    publicationDate: "",
    coverImageFileIds: "",
    isbn: "",
    pages: "",
    price: "",
    author: "",
    originalName: "",
    translator: "",
    top: false,
    topIndex: 0,
    readCount: 0,
    status: 1,
    description: "",
    aboutTheAuthor: "",
    tableOfContents: "",
    content: "",
    fileIds: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  publicationName: [
    { required: true, message: () => t("common.required"), trigger: "blur" },
  ],
});

const handleAffixScroll = (value: { scrollTop: number; fixed: boolean }) => {
  // console.log("handleAffixScroll", value);
  if (value.scrollTop > 300) {
    // 动态移动编辑器工具栏
    var toolbar = document.getElementById("toolbar-container");
    var affixContainer = document.getElementById("affix-container").children[0];
    affixContainer.appendChild(toolbar);
  } else {
    var toolbar = document.getElementById("toolbar-container");
    var toolbarContainer = document.getElementById("affix-reset-container");
    toolbarContainer.appendChild(toolbar);
  }
};

//#region upload list image
const handleLogoUploadExceed = (files: any) => {
  // 超过限制数量自动替换旧文件
  // console.log("handleLogoUploadExceed", files);
  logoFileRef.value!.clearFiles();
  const file = files[0] as any;
  logoFileRef.value!.handleStart(file);
  logoFileRef.value!.submit();
};
const handleLogoUploadSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any
) => {
  if (response.code == 200) {
    // 更新服务器端主键
    uploadFile.uid = response.data.fileId;
  }
  //uploadFile: {uid:1234, name:"xxx", size:1234, url:"xxx",raw:{}, response:{}}
  // console.log("handleLogoUploadSuccess response", response);
  // console.log("handleLogoUploadSuccess uploadFile", uploadFile);
  // console.log("handleLogoUploadSuccess uploadFiles", uploadFiles);
};
//#endregion

//#region editor
// https://ckeditor.com/docs/ckeditor5/latest/installation/integrations/vuejs-v3.html
// Integrating a build from the online builder

let ckeditor = null as any;
class MyUploadAdapter {
  loader = null;
  constructor(loader) {
    this.loader = loader;
  }

  async upload() {
    const data = new FormData();
    data.append("file", await this.loader.file);
    data.append("category", "publication-detail-image");
    data.append("businessKey", formEdit.publicationId);
    const res = await axios({
      url: apiUpload.uploadUrl(),
      method: "POST",
      data,
      withCredentials: false, // true 为不允许带 token, false 为允许
      headers: headers(),
    });

    console.log(res.data);
    return {
      default: apiUpload.editorUrl(res.data.data.fileId),
    };
  }
}

const initCKEditor = (html) => {
  // https://ckeditor.com/docs/ckeditor5/latest/examples/builds/classic-editor.html
  // DecoupledEditor.defaultConfig = {};
  // export default class ClassicEditor extends ClassicEditorBase {}
  const editorPlaceholder = document.querySelector("#editor") as HTMLElement;
  DecoupledEditor.create(editorPlaceholder, {
    // removePlugins: [ 'Heading' ],
    // plugins: [],
    language: "zh-cn",
    toolbar: {
      items: [
        "heading",
        "|",
        // "fontsize",
        // "fontfamily",
        // "|",
        "bold",
        "italic",
        "underline",
        "strikethrough",
        "highlight",
        "|",
        "alignment",
        "|",
        "numberedList",
        "bulletedList",

        "|",
        "comment",
        "commentsArchive",
        "trackChanges",
        "|",
        "mediaEmbed",
        "imageUpload",
        "link",
        "blockquote",
        "insertTable",
        "|",
        "undo",
        "redo",
      ],
    },

    image: {
      resizeUnit: "px",
      resizeOptions: [
        {
          name: "resizeImage:original",
          value: null,
          icon: "original",
        },
        {
          name: "resizeImage:medium",
          value: "200",
          icon: "medium",
        },
        {
          name: "resizeImage:large",
          value: "400",
          icon: "large",
        },
      ],
      toolbar: [
        "imageTextAlternative",
        "toggleImageCaption",
        "|",
        // "imageStyle:inline",
        "imageStyle:wrapText",
        "imageStyle:breakText",
        // "imageStyle:side",
        "|",
        "resizeImage:medium",
        "resizeImage:large",
        "resizeImage:original",
      ],
    },
    table: {
      contentToolbar: ["tableColumn", "tableRow", "mergeTableCells"],
      tableToolbar: ["comment"],
    },
    mediaEmbed: {
      toolbar: ["comment"],
    },
  })
    .then((newEditor) => {
      const toolbarContainer = document.querySelector("#toolbar-container");
      toolbarContainer.appendChild(newEditor.ui.view.toolbar.element);

      console.log("newEditor.plugins", newEditor.plugins);
      newEditor.plugins.get("FileRepository").createUploadAdapter = (
        loader
      ) => {
        return new MyUploadAdapter(loader);
      };

      newEditor.setData(html);
      ckeditor = newEditor;
    })
    .catch((error) => {
      console.error("initCKEditor", error);
    });
};
//#endregion

const handleSubmit = async () => {
  await formRef.value.validate();

  // console.log("handleSubmit", typeof state.publicationDate, state.publicationDate == "");
  // 第一次 ""，后续修改为 object
  if (state.publicationDate == "" || state.publicationDate == null) {
    // formEdit.birthday = moment().format("YYYY-MM-DD");
    formEdit.publicationDate = "";
  } else if (typeof state.publicationDate == "object") {
    formEdit.publicationDate = moment(state.publicationDate).format(
      "YYYY-MM-DD"
    );
  }

  //   state.channelList.forEach((m) => {
  //     if (m.channelId == formEdit.channelId) {
  //       formEdit.channelName = m.name;
  //     }
  //   });

  //   formEdit.tags = "";
  //   dynamicTags.value.forEach((m) => {
  //     formEdit.tags += m + ",";
  //   });
  //   if (formEdit.tags.length > 0) {
  //     formEdit.tags = formEdit.tags.substring(0, formEdit.tags.length - 1);
  //   }

  //   let fileIds = "";
  //   logoFileList.value.forEach((file) => {
  //     fileIds += file.uid + ",";
  //   });

  let fileIds = "";

  if (logoFileList.value.length == 0) {
    utils.infoNotification(t("publication.uploadListImage"));
    return;
  }
  formEdit.coverImageFileIds = logoFileList.value[0].uid;

  fileIds = formEdit.coverImageFileIds;

  formEdit.fileIds = fileIds;
  // let html = ckeditorRef.value.getData();
  // formEdit.content = html;

  let html = ckeditor.getData();
  formEdit.content = utils.base64Encode(html);

  if (formEdit.top == false) {
    formEdit.topIndex = 0;
  }

  // 处理业务逻辑，触发关闭事件
  apiPublication
    .savePublication(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      // 还原原文
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (row: any) => {
  // tags
  //   inputValue.value = "";
  //   dynamicTags.value = [];
  //   inputVisible.value = false;

  //   state.taglList = Array<any>();
  state.publicationDate = null;
  state.tagPage = 1;
  state.tagMore = true;
  logoFileList.value = [];

  //   apiCms
  //     .loadAllChannel()
  //     .then((response: any) => {
  //       if (response.data.code == 200) {
  //         Object.assign(state.channelList, response.data.data);
  //       }
  //     })
  //     .catch((err: any) => {
  //       utils.errorNotification(t("common.submitException"), err);
  //     });

  Object.assign(formEdit, formEditOriginal());
  if (row != undefined) {
    apiPublication
      .getPublication(row.publicationId)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);
          Object.assign(formEdit, response.data.detail);
          console.log("assign2", formEdit);
          //   if (formEdit.tags.length > 0) {
          //     dynamicTags.value = formEdit.tags.split(",");
          //   }
          //   if (
          //     (formEdit.listLayout == 1 || formEdit.listLayout == 2) &&
          //     formEdit.listImageFileIds.length > 0
          //   ) {
          //     formEdit.listImage0FileId = formEdit.listImageFileIds;
          //   }

          logoFileList.value.push({
            uid: formEdit.coverImageFileIds,
            name: formEdit.coverImageFileIds,
            url: apiUpload.downloadUrl(formEdit.coverImageFileIds),
          });

          state.publicationDate = formEdit.publicationDate;
          // console.log("state.publicationDate", formEdit.publicationDate);

          if (formEdit.topIndex > 0) {
            formEdit.top = true;
          } else {
            formEdit.topIndex = 0;
          }

          setTimeout(() => {
            initCKEditor(response.data.detail.content);
          }, 500);
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  } else {
    // 初始化id
    apiCms
      .generateId()
      .then((response: any) => {
        if (response.data.code == 200) {
          formEdit.publicationId = response.data.data;
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });

    setTimeout(() => {
      initCKEditor("");
    }, 1000);
  }

  //   handleQueryTag();

  state.dialogFormVisible = true;
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 强制立即执行侦听，组件启动就获取一次值
const unwatch = watch(
  () => formEdit.top,
  (newValue, oldValue) => {
    if (newValue == false) {
      formEdit.topIndex = 0;
    }
  },
  { deep: true, immediate: true }
);

onUnmounted(() => {
  unwatch();
});

const onDialogClose = () => {
  if (ckeditor) {
    ckeditor.destroy();
  }
  state.dialogFormVisible = false;
};

defineExpose({
  show,
});
</script>
<style lang="scss">
#editor {
  display: block;
  min-height: 780px;
  width: 750px;
  .table {
    display: table;
    min-width: 400px;
    margin: 0.9em auto;
    table {
      border: 1px double #b3b3b3;
      border-collapse: collapse;
      border-spacing: 0;
      height: 100%;
      width: 100%;
    }
  }
}
.ck-editor__editable {
  // min-height: 780px;
  // width: 750px;
  // border: 1px solid #4878e3 !important;
  border-radius: 2px;
  box-shadow: 2px 2px 3px var(--ck-color-shadow-inner) inset, 0 0;

  p {
    overflow-wrap: break-word;
    word-wrap: break-word;
    font-size: 18px;
    color: rgb(51, 51, 51);
    line-height: 34px;
    margin-bottom: 30px;
  }

  font: 400 1em/1.8 "PingFang SC", "Microsoft Yahei", "Avenir", "Segoe UI",
    "Hiragino Sans GB", "STHeiti", "Microsoft Sans Serif", "WenQuanYi Micro Hei",
    sans-serif;
}
.ck-powered-by {
  display: none;
}
.ck-body-wrapper {
  z-index: 1300 !important;
}
</style>
